package com.haoma.interceptor;

import com.haoma.constant.RedisConstant;
import com.haoma.utils.JwtHelper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * Description: 登录拦截器
 */
public class LoginMvcInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public LoginMvcInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 在请求之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 答应请求信息
        System.out.println(request.getContextPath());
        // 获取并打印请求路径
        String requestUri = request.getRequestURI();
        System.out.println("Request URI: " + requestUri);
        // 从请求头中获取token
        String token = request.getHeader("authorization");
        // 判断
        if (!StringUtils.hasText(token)) {
            // 为空抛出401
            response.setStatus(401);
            return false;
        }
        // 查询redis
        String s = stringRedisTemplate.opsForValue().get("visitor");
        if (s != null && s.equals("visitorviewingrightstoken")) {
            return true;
        }
        // 解析token
        Long userId = null;
        try {
            userId = JwtHelper.getUserId(token);
        } catch (Exception e) {
            stringRedisTemplate.delete(RedisConstant.USER_LOGIN_KEY_PREFIX + 1);
            // token过期了
            response.setStatus(401);
            return false;
        }
        if (userId == null) {
            response.setStatus(401);
            return false;
        }
        String key = RedisConstant.USER_LOGIN_KEY_PREFIX + userId;
        // 查询redis中是否存在该用户
        String redisToken = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.hasText(redisToken)) {
            // 有token更新过期时间
            stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);
            // 结束
            return true;
        }
        // 不存在存入redis中
        stringRedisTemplate.opsForValue().set(key, token, 30, TimeUnit.MINUTES);
        return true;
    }
}
